package com.edison.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Supplier;

/**
 * @author edison
 * data service
 */
@Slf4j
public class BaseDataService {
    public static <T> CompletableFuture<List<T>> initData(int number, Supplier<T> generator) {
        List<T> dataList = new ArrayList<>();
        for (int i = 0; i < number; i++) {
            dataList.add(generator.get());
        }
        return CompletableFuture.completedFuture(dataList);
    }


    public static <T> CompletableFuture<Integer> batchInsert(
            List<T> list,
            int batchSize,
            BiFunction<List<T>, Integer, List<BatchResult>> inserter
    ) {
        List<BatchResult> batchResults = inserter.apply(list, batchSize);
        AtomicInteger updateCounts = new AtomicInteger();
        batchResults.forEach(batchResult -> updateCounts.addAndGet(batchResult.getUpdateCounts().length));
        return CompletableFuture.completedFuture(updateCounts.intValue());
    }



    private BaseDataService() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }

}
